using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using Ajax;

namespace BA.Chat
{
    public class ChatEngine
    {
        // Fields
        protected static ArrayList pArray = new ArrayList();

        // Methods
        [AjaxMethod]
        public void AddMessage(string sUser, string sMsg)
        {
            string sAddText = "<STRONG>" + sUser + " says: </STRONG>" + this.CheckForLink(sMsg);
            pArray.Add(sAddText);
            if (pArray.Count > 200)
            {
                pArray.RemoveRange(0, 10);
            }
        }

        public bool check()
        {
            if (pArray.Count == 0)
            {
                return false;
            }
            return true;
        }

        private string CheckForLink(string msg)
        {
            string pattern3 = @"\s(((h|H?)(t|T?)(t|T?)(p|P?)(s|S?))*://)?(www.|[a-zA-Z0-9].)[a-zA-Z0-9\-\.]+\.[a-zA-Z]?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]*";
            Regex expression = new Regex(pattern3, RegexOptions.IgnoreCase);
            return expression.Replace(msg, new MatchEvaluator(this.ReplaceLink));
        }

        [AjaxMethod]
        public void Clean()
        {
            pArray.Clear();
        }

        protected string FixHttpPrefix(string URLLink)
        {
            if (Microsoft.VisualBasic.Strings.InStr(URLLink, "http://", Microsoft.VisualBasic.CompareMethod.Text) == 0)
            {
                return ("http://" + URLLink);
            }
            return URLLink;
        }

        [AjaxMethod]
        public string GetAllMessages()
        {
            string sResponse = "";
            for (int i = 0; i < pArray.Count; i++)
            {
                sResponse = sResponse + "<BR>" + pArray[i].ToString();
            }
            return sResponse;
        }

        public void joinRoom(string sUser)
        {
            string sAddText = "<STRONG>" + sUser + " has joined the room</STRONG>";
            pArray.Add(sAddText);
        }

        public void leaveRoom(string sUser)
        {
            string sAddText = "<STRONG>" + sUser + " has left the room</STRONG>";
            pArray.Add(sAddText);
        }

        private string ReplaceLink(Match m)
        {
            if (m.Value.IndexOf(" ") == 0)
            {
                return string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", this.FixHttpPrefix(m.Value.Remove(0, 1).ToString()), m.Value);
            }
            return string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", this.FixHttpPrefix(m.Value), m.Value);
        }
    }
}
